var express = require('express');
var domain = require('domain');

global.gg = require('./common');

process.on('uncaughtException', function (err) {
	console.log('系统异常*******************');
	console.log(err.stack);
	console.log('系统异常*******************');
});

var app = express();

var sessionStore = new express.session.MemoryStore;

app.use(express.static(__dirname + '/../projects'));
//app.use(express.logger());
app.use(express.cookieParser());
app.use(express.session({
	secret:'oyster_secret',
	store:sessionStore
}));
app.use(express.bodyParser());

app.use(function(req, res, next){
	var d = domain.create();
	d.on('error', function(err){
		console.log(new Date() , ':发生严重错误**********************');
		console.log(err.stack);
		res.json({code:600, data:'syserror'});
		console.log('严重错误**********************');
		d.dispose();
	});
	d.add(req);
	d.add(res);
	d.run(next);
});

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.send(500, 'Something broke!');
});


var routes = require("./routes/index");
for(var i in routes){
	if(typeof routes[i] === 'function'){
		app.all('/user/' + i, routes[i]);
	}
}

app.get('/', function (req, res) {
	res.setHeader('Content-Type', 'text/json');
	res.send('Oyster Server!');
});

//定时检查用户数量 清理超时用户
setInterval(function(){
	//清理垃圾session 无效session
	for(var i in sessionStore.sessions){
		var match = sessionStore.sessions[i].match(/"uid":"(.*?)"/);
		if(match){
			var uid = match[1];
			if(!userManager.users[uid]){
				console.log('销毁带uid的session', uid);
				sessionStore.destroy(i);
			}
		}
		else{
			console.log('销毁无uid的session', sessionStore.sessions[i]);
			sessionStore.destroy(i);
		}
	}

	//清理不活跃用户
	var now = Date.now();
	for(var i in userManager.users){
		var user = userManager.users[i];
		if(user.lastActiveTime && (now - user.lastActiveTime) < config.userTimeout){
		}
		else{
			userManager.logout(i, function(){});
		}
	}
}, config.scanInterval);

//服务器关机处理 Ctrl + C
process.on('SIGINT', function() {
  var users = [];
  for(var i in userManager.users){
    users.push(i);
  }
  console.log('正在将' + users.length + '个玩家数据写入数据库中，请稍候...');
  function flush(users){
	if(users.length > 0){
		var user = users.pop();
		userManager.logout(user, function(){
			flush(users);//递归调用
		});
	}
	else{
		console.log('服务器已经关闭');
		process.exit();
	}
  }
  flush(users);
});

app.listen(config.port);
console.log('Oyster Server Start...');
